package MLDA_Process;

//import gnu.trove.list.array.TDoubleArrayList;

import gnu.trove.map.hash.TIntIntHashMap;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import Commons.IOUtil;

public class HPAM4ST_V2 implements Runnable {

    public int P = 1000;
    public int K = 100;

    public int M;
    public int V;

    public double alpha1 = 0.1;
    public double alpha2 = 0.1;

    public double beta0 = 0.001;
    public double beta1 = 0.01;

    public double gamma0 = 0.1;
    public double gamma1 = 0.1;

    public int mp[];

    public int npk[][];
    public int np[];

    public int nwk[][];
    public int nk[];

    public int ndwSum[];
    TIntIntHashMap ndw[];


    public int z1_assigns[];
    public int z2_assigns[][];

    public int x_assigns[][];

    public int niters = 2000;
    public int saveStep = 1000;
    public String inputPath = "";
    public String outputPath = "";


    public List<List<Integer>> docs = new ArrayList<List<Integer>>();
    public HashMap<String, Integer> w2i = new HashMap<String, Integer>();
    public HashMap<Integer, String> i2w = new HashMap<Integer, String>();

    public HPAM4ST_V2(int P, int K, int iter, int saveStep, double alpha1, double alpha2, double beta0, double beta1, String inputPath, String outputPath) {
        this.P = P;
        this.K = K;
        this.alpha1 = alpha1;
        this.alpha2 = alpha2;
        this.beta0 = beta0;
        this.beta1 = beta1;
        this.niters = iter;
        this.saveStep = saveStep;
        this.inputPath = inputPath;
        this.outputPath = outputPath;
    }

    public void loadTxts(String txtPath) {
        BufferedReader reader = IOUtil.getReader(txtPath, "UTF-8");

        String line;
        try {
            line = reader.readLine();
            while (line != null) {
                List<Integer> doc = new ArrayList<Integer>();

                String[] tokens = line.trim().split("\\s+");
                for (String token : tokens) {
                    if (!w2i.containsKey(token)) {
                        w2i.put(token, w2i.size());
                        i2w.put(w2i.get(token), token);
                    }
                    doc.add(w2i.get(token));
                }
                docs.add(doc);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        M = docs.size();
        V = w2i.size();

        return;
    }

    public void init_model() {
        mp = new int[P];

        npk = new int[P][K];
        np = new int[P];

        nwk = new int[V][K];
        nk = new int[K];

        ndw = new TIntIntHashMap[M];
        ndwSum = new int[M];

        z1_assigns = new int[M];
        z2_assigns = new int[M][];
        x_assigns = new int[M][];

        for (int m = 0; m != M; m++) {
            int N = docs.get(m).size();
            z2_assigns[m] = new int[N];
            x_assigns[m] = new int[N];

            int z1 = (int) Math.floor(Math.random() * P);
            z1_assigns[m] = z1;

            mp[z1]++;

            ndw[m] = new TIntIntHashMap();

            for (int n = 0; n != N; n++) {
                int w = docs.get(m).get(n);
                int z2 = (int) Math.floor(Math.random() * K);
                int x = (int) Math.floor(Math.random() * 2);

                if (x != 0) {
                    nwk[w][z2]++;
                    nk[z2]++;
                    npk[z1][z2]++;
                    np[z1]++;
                } else {
                    ndw[m].adjustOrPutValue(w, 1, 1);
                    ndwSum[m]++;
                }

                z2_assigns[m][n] = z2;
                x_assigns[m][n] = x;
            }
        }
    }


    public void sample_z1(int m) {
        int z1 = z1_assigns[m];
        int N = docs.get(m).size();

        mp[z1]--;

        TIntIntHashMap k2Count = new TIntIntHashMap();
        for (int n = 0; n != N; n++) {
            int z2 = z2_assigns[m][n];
            int x = x_assigns[m][n];
            if (x != 0) {
                k2Count.adjustOrPutValue(z2, 1, 1);
                npk[z1][z2]--;
                np[z1]--;
            }
        }

        double[] pTable = new double[P];

        for (int p = 0; p != P; p++) {
            double expectTM = 1.0;
            int index = 0;
            for (int z2 : k2Count.keys()) {
                int c = k2Count.get(z2);
                for (int i = 0; i != c; i++) {
                    expectTM *= (npk[p][z2] + alpha2 + i) / (alpha2 * K + np[p] + index++);
                }
            }

            pTable[p] = (mp[p] + alpha1) * expectTM;
        }

        for (int p = 1; p != P; p++) {
            pTable[p] += pTable[p - 1];
        }

        double r = Math.random() * pTable[P - 1];

        for (int p = 0; p != P; p++) {
            if (pTable[p] > r) {
                z1 = p;
                break;
            }
        }

        mp[z1]++;
        for (int n = 0; n != N; n++) {
            int z2 = z2_assigns[m][n];
            int x = x_assigns[m][n];
            if (x != 0) {
                npk[z1][z2]++;
                np[z1]++;
            }
        }

        z1_assigns[m] = z1;
    }

    public void sample_z2(int m, int n) {
        int z1 = z1_assigns[m];
        int z2 = z2_assigns[m][n];
        int x = x_assigns[m][n];
        int w = docs.get(m).get(n);

        if (x != 0) {
            nwk[w][z2]--;
            nk[z2]--;
            npk[z1][z2]--;
            np[z1]--;
        } else {
            ndw[m].adjustValue(w, -1);
            ndwSum[m]--;
        }

        double vBeta0 = V * beta0;
        double vBeta1 = V * beta1;
        double KAlpha2 = K * alpha2;
        double dGamma = gamma0 + gamma1;

        double[] pTable = new double[K + 1];

        for (int k = 0; k != K + 1; k++) {
            if (k == 0) {
                pTable[k] = (ndwSum[m] + gamma0) / (docs.get(m).size() + dGamma) *
                        (ndw[m].get(w) + beta0) / (ndwSum[m] + vBeta0);
            } else {
                pTable[k] = (docs.get(m).size() - ndwSum[m] + gamma1) / (docs.get(m).size() + dGamma) *
                        (npk[z1][k - 1] + alpha2) / (np[z1] + KAlpha2) *
                        (nwk[w][k - 1] + beta1) / (nk[k - 1] + vBeta1);
            }
        }

        for (int k = 1; k != K + 1; k++) {
            pTable[k] += pTable[k - 1];
        }

        double r = Math.random() * pTable[K];

        for (int k = 0; k != K + 1; k++) {
            if (pTable[k] > r) {
                z2 = k;
                break;
            }
        }

        if (z2 != 0) {
            z2 -= 1;
            nwk[w][z2]++;
            nk[z2]++;
            npk[z1][z2]++;
            np[z1]++;
            x = 1;
        } else {
            ndw[m].adjustValue(w, 1);
            ndwSum[m]++;
            x = 0;
        }

        x_assigns[m][n] = x;
        z2_assigns[m][n] = z2;
    }

    public void estimate() {
        for (int iter = 0; iter != niters; iter++) {
            System.out.println("HPAM4ST_V2 Iteration: " + iter + " ...");
            if (iter % this.saveStep == 0 && iter != 0 && iter != this.niters - 1) {
                this.storeResult(iter);
            }
            Long begin = System.currentTimeMillis();
            for (int m = 0; m != M; m++) {
                this.sample_z1(m);
            }
            for (int m = 0; m != M; m++) {
                int N = docs.get(m).size();
                for (int n = 0; n != N; n++) {
                    sample_z2(m, n);
                }
            }
            if (iter % 500 == 0 && iter != 0) {
                this.saveTheta("/Users/zuoyuan/Desktop/tweet_theta_hpamv2_" + iter + ".txt");
            }
            System.out.println((System.currentTimeMillis() - begin) / 1000.0);
        }
        return;
    }

    public double[][] computePhi() {
        double[][] phi = new double[K][V];
        for (int k = 0; k != K; k++) {
            for (int v = 0; v != V; v++) {
                phi[k][v] = (nwk[v][k] + beta1) / (nk[k] + V * beta1);
            }
        }
        return phi;
    }

    int ndk[][];
    int ndkSum[];
    double alpha = 0.1;

    public void convert_zassigns_to_arrays_theta() {
        ndk = new int[M][K];
        ndkSum = new int[M];

        for (int m = 0; m != M; m++) {
            for (int n = 0; n != docs.get(m).size(); n++) {
                if (x_assigns[m][n] != 0) {
                    ndk[m][z2_assigns[m][n]]++;
                    ndkSum[m]++;
                }
            }
        }
    }

    public double[][] computeTheta() {
        this.convert_zassigns_to_arrays_theta();
        double[][] theta = new double[M][K];
        for (int m = 0; m != M; m++) {
            for (int k = 0; k != K; k++) {
                theta[m][k] = (ndk[m][k] + alpha) / (ndkSum[m] + K * alpha);
            }
        }
        return theta;
    }

    public ArrayList<List<Entry<String, Double>>> sortedTopicWords(
            double[][] phi, int T) {
        ArrayList<List<Entry<String, Double>>> res = new ArrayList<List<Entry<String, Double>>>();
        for (int k = 0; k != T; k++) {
            HashMap<String, Double> term2weight = new HashMap<String, Double>();
            for (String term : w2i.keySet())
                term2weight.put(term, phi[k][w2i.get(term)]);

            List<Entry<String, Double>> pairs = new ArrayList<Entry<String, Double>>(
                    term2weight.entrySet());
            Collections.sort(pairs, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> o1,
                                   Entry<String, Double> o2) {
                    return (o2.getValue().compareTo(o1.getValue()));
                }
            });
            res.add(pairs);
        }
        return res;
    }

    public void printTopics(String path, int top_n) throws IOException {
        BufferedWriter writer = IOUtil.getWriter(path);
        double[][] phi = computePhi();
        ArrayList<List<Entry<String, Double>>> pairsList = this
                .sortedTopicWords(phi, K);
        for (int k = 0; k != K; k++) {
            writer.write("Topic " + k + ":\n");
            for (int i = 0; i != top_n; i++) {
                writer.write(pairsList.get(k).get(i).getKey() + " "
                        + pairsList.get(k).get(i).getValue() + "\n");
            }
        }
        writer.close();
    }

    public void savePhi(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");

        double[][] phi = computePhi();
        try {
            for (int k = 0; k != K; k++) {
                for (int v = 0; v != V; v++) {
                    writer.append(phi[k][v] + " ");
                }
                writer.append("\n");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void saveTheta(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");

        double[][] theta = computeTheta();

        try {
            for (int m = 0; m != M; m++) {
                for (int k = 0; k != K; k++) {
                    writer.append(theta[m][k] + " ");
                }
                writer.append("\n");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void saveZ2Assigns(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");
        try {
            for (int m = 0; m != M; m++) {
                for (int n = 0; n != docs.get(m).size(); n++) {
                    writer.append(docs.get(m).get(n) + ":" + z2_assigns[m][n] + " ");
                }
                writer.append("\n");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void saveXAssigns(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");
        try {
            for (int m = 0; m != M; m++) {
                for (int n = 0; n != docs.get(m).size(); n++) {
                    writer.append(i2w.get(docs.get(m).get(n)) + ":" + x_assigns[m][n] + " ");
                }
                writer.append("\n");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void saveWordmap(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");

        try {
            for (String word : w2i.keySet())
                writer.append(word + "\t" + w2i.get(word) + "\n");

            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void printModel() {
        System.out.println("P :" + this.P +
                "\tK :" + this.K +
                "\tniters :" + this.niters +
                "\tsaveStep :" + this.saveStep +
                "\talpha1 :" + this.alpha1 +
                "\talpha2 :" + this.alpha2 +
                "\tbeta0 :" + this.beta0 +
                "\tbeta1 :" + this.beta1 +
                "\tinputPath :" + this.inputPath +
                "\toutputPath :" + this.outputPath);
    }

    public void storeResult(int times) {
        String appendString = "final";
        if (times != 0) {
            appendString = times + "";
        }
        try {
            this.printTopics(outputPath + "/model-" + appendString + ".twords", 20);
            this.saveWordmap(outputPath + "/wordmap.txt");
            this.savePhi(outputPath + "/model-" + appendString + ".phi");
            this.saveZ2Assigns(outputPath + "/model-" + appendString + ".tassign");
            this.saveTheta(outputPath + "/model-" + appendString + ".theta");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void run() {
        printModel();
        this.loadTxts(inputPath);//
        this.init_model();
        this.estimate();
        this.storeResult(0);

    }

    public static void HPAMForShortText_V2(int P, int K, int iter, int saveStep, double alpha1, double alpha2, double beta0, double beta1, int threadNum, String path) {
        ExecutorService service = Executors.newCachedThreadPool();
        File trainFile = new File(path);
        String parent_path = trainFile.getParentFile().getAbsolutePath() + "/HPAM4ST_V2_" + P + "_" + K + "_" + alpha1 + "_" + alpha2 + "_" + beta0 + "_" + beta1 + "/";
        for (int i = 0; i < threadNum; i++) {
            (new File(parent_path + i)).mkdirs();
            service.submit(new HPAM4ST(P, K, iter, saveStep, alpha1, alpha2, beta0, beta1, path, parent_path + i));

        }
        service.shutdown();
    }
}
